package com.xszx.server.service;

import com.xszx.server.dto.Page;
import com.xszx.server.entity.UploadFile;
import com.xszx.server.mapper.UploadFileMapper;
import com.xszx.server.util.UuidUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.Date;

@Service
public class UploadFileService {
    @Resource
    private UploadFileMapper uploadFileMapper;

    /**
     * 获取分页列表
     * @param page
     * @return
     */
    public Page getAllUploadFiles(Page page){
        int pageNum = page.getPage();
        page.setPage((page.getPage()-1)*page.getSize());
        page.setList(uploadFileMapper.findAll(page));
        page.setTotal(uploadFileMapper.findCount());
        page.setPage(pageNum);
        return page;
    }

    /**
     * 新增或者删除信息
     * @param uploadFile
     * @return
     */
    public String saveOrUpdate(UploadFile uploadFile){
        //查看数据库中是否有当前视频的数据
        UploadFile upFile = uploadFileMapper.selectByFileKey(uploadFile.getFileKey());
        if(upFile == null){
            Date now = new Date();
            uploadFile.setCreatedAt(now);
            uploadFile.setUpdatedAt(now);
            uploadFile.setId(UuidUtil.getShortUuid());
            return (uploadFileMapper.insert(uploadFile)>0)?"添加成功":"添加失败";
        }else{
            uploadFile.setUpdatedAt(new Date());
            uploadFile.setId(upFile.getId());
            uploadFile.setCreatedAt(upFile.getCreatedAt());
            return (uploadFileMapper.updateByPrimaryKey(uploadFile)>0)?"更新成功":"更新失败";
        }
    }

    /**
     * 物理删除文件
     * @param id
     * @return
     */
    public int del(String id){
        return uploadFileMapper.deleteByPrimaryKey(id);
    }
     /**
     * 获取单个文件
     * @return
     */
    public UploadFile getUploadFile(String id){
        return uploadFileMapper.selectByPrimaryKey(id);
    }

    /**
     * 获取file_key单个文件
     * @return
     */
    public UploadFile getUploadFileByFileKey(String fileKey){
        return uploadFileMapper.selectByFileKey(fileKey);
    }
}
